﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Commons;
using WebApp.Data;
using WebApp.Services;
using MvcJqGrid;
using PagedList;

namespace WebApp.Controllers
{
    public class BlockController : Controller
    {

        private BlockService _service;

        #region | Index |

        //
        // GET: /Block/
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult BlockList(GridSettings gridSettings, string keyword)
        {
            _service = new BlockService();

            var realCount = 0;

            var datas = _service.BlockList(gridSettings.PageIndex,
                                          gridSettings.PageSize,
                                          gridSettings.SortColumn,
                                          gridSettings.SortOrder,
                                          keyword,
                                          ref realCount);

            var totalBUs = realCount;
            var totalPage = totalBUs / gridSettings.PageSize;

            if (totalPage > Convert.ToInt32(totalPage))
            {
                totalPage = totalPage + 1;
            }

            var jsonData = new
            {
                total = Convert.ToInt32(totalPage),
                page = gridSettings.PageIndex,
                records = totalBUs,
                rows = (
                            from c in datas
                            select new
                            {
                                id = c.block_id,
                                cell = new[] {
                                            c.block_id.ToString(CultureInfo.InvariantCulture),
                                            c.block_code,
                                            c.block_wide.ToString() + " x " + c.block_long,
                                            c.block_create_date.HasValue ? c.block_create_date.Value.ToLongDateString() : "",
                                            "<div style='width: 55px; height: 20px; background-color: #" + "ccooff" + ";'></div>"
                                            }
                            }
                        ).ToPagedList(1, gridSettings.PageSize).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult PriceList(GridSettings gridSettings, int matid)
        {
            _service = new BlockService();

            var realCount = 0;

            var datas = _service.GetMaterialPrice(gridSettings.PageIndex,
                                          gridSettings.PageSize,
                                          gridSettings.SortColumn,
                                          gridSettings.SortOrder,
                                          matid,
                                          ref realCount);

            var totalBUs = realCount;
            var totalPage = totalBUs / gridSettings.PageSize;

            if (totalPage > Convert.ToInt32(totalPage))
            {
                totalPage = totalPage + 1;
            }

            var jsonData = new
            {
                total = Convert.ToInt32(totalPage),
                page = gridSettings.PageIndex,
                records = totalBUs,
                rows = (
                            from c in datas
                            select new
                            {
                                id = c.id.ToString(),
                                cell = new[] {
                                            c.id.ToString(),
                                            c.sale_price == 0 ? "0" : c.sale_price.ToString(),
                                            c.purchase_price == 0 ? "0" : c.sale_price.ToString(),
                                            c.created_date.Value.ToLongDateString()
                                            }
                            }
                        ).ToPagedList(1, gridSettings.PageSize).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Update(tbl_material oModel, FormCollection formCollection)
        {
            _service = new BlockService();

            var isPass = false;
            var iMessage = string.Empty;

            var operation = formCollection["oper"];

            if (operation.Equals("add") || operation.Equals("edit"))
            {
                isPass = _service.Update(oModel);
            }

            return Json(new { isPass, iMessage });
        }

        public JsonResult Delete(int[] ids, FormCollection formCollection)
        {
            _service = new BlockService();

            var isPass = false;
            var iMessage = string.Empty;

            var operation = formCollection["oper"];

            if (operation.Equals("del"))
            {
                isPass = _service.Delete(ids);
            }

            return Json(new { isPass, iMessage });
        }

        public String GetMaterialType()
        {
            var sTag = DataProvider.GetMaterialType().Aggregate("<select>", (current, type) => current + "<option value='" + type.material_type_id + "'>" + type.material_type_name + "</option>");

            return sTag + "</select>";
        }

        #endregion

        #region | Detail |

        public ActionResult Detail(int id, string backurl)
        {
            _service = new BlockService();

            var model = _service.GetBlock(id);
            ViewBag.Serie = GetSeries(model.series_id.HasValue ? model.series_id.Value : 0).series_name;
            ViewBag.CreatedBy = GetUserName(model.block_create_by.Value);
            ViewBag.UpdatedBy = GetUserName(model.block_update_by.Value);

            return View(model);
        }

        public ActionResult DetailBack(int id, string outline)
        {
            _service = new BlockService();

            var model = _service.GetBlock(id);
            model.block_outline_ = outline;

            return RedirectToAction("Detail", "Block", model);
        }

        private tbl_serie GetSeries(int seriesId)
        {
            using (var db = new PAVINGDataContext())
            {
                return db.tbl_series.SingleOrDefault(s => s.series_id == seriesId);
            }
        }

        public JsonResult ColorList(GridSettings gridSettings, int blockId)
        {
            _service = new BlockService();

            var realCount = 0;

            var datas = _service.ColorList(gridSettings.PageIndex,
                                          gridSettings.PageSize,
                                          gridSettings.SortColumn,
                                          gridSettings.SortOrder,
                                          blockId,
                                          ref realCount);

            var totalBUs = realCount;
            var totalPage = totalBUs / gridSettings.PageSize;

            if (totalPage > Convert.ToInt32(totalPage))
            {
                totalPage = totalPage + 1;
            }

            var jsonData = new
            {
                total = Convert.ToInt32(totalPage),
                page = gridSettings.PageIndex,
                records = totalBUs,
                rows = (
                            from c in datas
                            select new
                            {
                                id = c.material_id,
                                cell = new[] {
                                            c.material_id.ToString(CultureInfo.InvariantCulture),
                                            c.material_name,
                                            "<div style='width: 55px; height: 20px; background-color: #" + c.block_color_code + ";'></div>",
                                            c.sale_price == null ? "0" : c.sale_price.ToString(),
                                            c.purchase_price == null ? "0" : c.purchase_price.ToString(),
                                            c.material_create_date.HasValue ? c.material_create_date.Value.ToLongDateString() : ""
                                           }
                            }
                        ).ToPagedList(1, gridSettings.PageSize).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region | Edit |

        public ActionResult Edit(int id)
        {
            _service = new BlockService();

            var model = _service.GetBlock(id);
            ViewBag.Series = SelectSeries();

            return View(model);
        }

        public List<SelectListItem> SelectSeries()
        {

            var items = new List<SelectListItem>();

            using (var db = new PAVINGDataContext())
            {
                var series = db.tbl_series;

                foreach (var serie in series)
                {
                    items.Add(new SelectListItem { Text = serie.series_name, Value = serie.series_id.ToString() });
                }

            }

            return items;
        }

        [HttpPost]
        public ActionResult Update(tbl_block model)
        {
            using (var db = new PAVINGDataContext())
            {
                var block = db.tbl_blocks.SingleOrDefault(b => b.block_id == model.block_id);

                if (block != null)
                {
                    block.series_id = model.series_id;
                    block.block_height = model.block_height;
                    block.block_weight = model.block_weight;
                    block.block_update_date = DateTime.Now;
                    block.block_update_by = PavingContext.CurrentUserId();

                    db.SubmitChanges();
                }
            }

            return RedirectToAction("Detail", "Block", new {id = model.block_id});
        }

        [HttpPost]
        public ActionResult UpdateEdit(tbl_block model)
        {
            using (var db = new PAVINGDataContext())
            {
                var block = db.tbl_blocks.SingleOrDefault(b => b.block_id == model.block_id);

                if (block != null)
                {
                    block.block_wide = model.block_wide;
                    block.block_long = model.block_long;
                    block.block_outline_ = model.block_outline_;
                    block.block_update_date = DateTime.Now;
                    block.block_update_by = PavingContext.CurrentUserId();

                    db.SubmitChanges();
                }
            }

            return RedirectToAction("Edit", "Block", new { id = model.block_id });
        }

        private string GetUserName(int userId)
        {
            try
            {
                using (var db = new PAVINGDataContext())
                {
                    var user = db.tbl_users.SingleOrDefault(u => u.user_id == userId);

                    if (user != null)
                        return user.user_login_name;
                    else
                        return string.Empty;
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        #endregion

        #region | Designer |

        public ActionResult Designer(int id)
        {
            _service = new BlockService();

            var model = _service.GetBlock(id);

            return View(model);
        }

        #endregion

        //        private BlockService _service;
//        public ActionResult Index()
//        {
//            InitialView();
//            return View();
//        }
//
//        public ActionResult BlockDesigner()
//        {
//            return View();
//        }
//
//        private void InitialView()
//        {
//            //Initial Block Series dropdown list
//            using (var db = new PAVINGDataContext())
//            {
//                var series = db.tbl_series.ToList();
//                var tbl = new tbl_serie() {series_id = 0,series_name = "All"};
//                series.Insert(0,tbl);
//                var sel = new SelectList(series, "series_id", "series_name");
//                
//                ViewBag.Dropdown = sel;
//                ViewBag.SelectedDropdown = sel;
//            }
//        }
//
//        private void InitialDropDown(int selectedValue)
//        {
//            using (var db = new PAVINGDataContext())
//            {
//                var series = db.tbl_series.ToList();
//                var tbl = new tbl_serie() { series_id = 0, series_name = "All" };
//                series.Insert(0, tbl);
//                var sel = new SelectList(series, "series_id", "series_name", selectedValue);
//
//                ViewBag.SelectedDropdown = sel;
//            }
//        }
//
//        public JsonResult GetSeriesName(tbl_serie serie)
//        {
//            //InitialDropDown(serie.series_id);
//            _service = new BlockService();
//            var seriesName = _service.GetSerieNameFromId(serie.series_id);
//            var jsonData = new
//            {
//                series_name = seriesName
//            };
//            return Json(jsonData, JsonRequestBehavior.AllowGet);
//        }
//
//        public JsonResult GetBlockFromSeries(GridSettings gridSettings,int seriesId)
//        {
//            _service = new BlockService();
//            var realCount = 0;
//            var datas = _service.GetBlockFromSeries(seriesId, ref realCount);
//            var jsonData = GetJsonBlockDataResult(datas, realCount, gridSettings);
//            return Json(jsonData, JsonRequestBehavior.AllowGet);
//        }
//
//        public JsonResult GetBlocksByKeywordOrSeries(GridSettings gridSettings, string keyword, int seriesId)
//        {
//            _service = new BlockService();
//
//            if (string.IsNullOrEmpty(keyword))
//                keyword = string.Empty;
//            var realCount = 0;
//            var datas = _service.GetBlocksByKeywordOrSeries(gridSettings.PageIndex,
//                                          gridSettings.PageSize,
//                                          gridSettings.SortColumn,
//                                          gridSettings.SortOrder,
//                                          keyword,seriesId,
//                                          ref realCount);
//            var jsonData = GetJsonBlockDataResult(datas, realCount, gridSettings);
//
//            return Json(jsonData, JsonRequestBehavior.AllowGet);
//        }
//
//        public JsonResult GetBlocks(GridSettings gridSettings, string keyword)
//        {
//            _service = new BlockService();
//
//            if (string.IsNullOrEmpty(keyword))
//                keyword = string.Empty;
//            var realCount = 0;
//            var datas = _service.GetBlocks(gridSettings.PageIndex,
//                                          gridSettings.PageSize,
//                                          gridSettings.SortColumn,
//                                          gridSettings.SortOrder,
//                                          keyword,
//                                          ref realCount);
//            var jsonData = GetJsonBlockDataResult(datas, realCount, gridSettings);
//
//            return Json(jsonData, JsonRequestBehavior.AllowGet);
//        }
//
//        private object GetJsonBlockDataResult(IEnumerable<tbl_block> datas, int realCount, GridSettings gridSettings)
//        {
//            var lists = new List<BlockModel>();
//            int pageSize = 0;
//            int pageIndex = 0;
//            if(gridSettings != null)
//            {
//                pageSize = gridSettings.PageSize;
//                pageIndex = gridSettings.PageIndex;
//            }
//
//            foreach (var model in datas)
//            {
//                var item = new BlockModel();
//                item.BlockId = model.block_id;
//                item.BlockName = model.block_code;
//                item.BlockWidth = model.block_width;
//                item.BlockWeigthLimit = model.block_weight;
//                item.BlockOutlineUrl = model.block_outline_;
//                item.SeriesId = model.series_id;
//                item.BlockCreateBy = model.block_create_by;
//                item.BlockCreateDate = model.block_create_date.HasValue ? model.block_create_date.Value : DateTime.Now;
//                item.BlockUpdateDate = model.block_update_date.HasValue ? model.block_update_date.Value : DateTime.Now;
//                item.BlockUpdateBy = model.block_update_by;
//                lists.Add(item);
//            }
//
//            var totalBUs = realCount;
//            var totalPage = totalBUs / pageSize;
//
//            if (totalPage > Convert.ToInt32(totalPage))
//            {
//                totalPage = totalPage + 1;
//            }
//
//            var jsonData = new
//            {
//                total = Convert.ToInt32(totalPage),
//                page = pageIndex,
//                records = totalBUs,
//                rows = (
//                            from e in lists
//                            select new
//                            {
//                                id = e.BlockId,
//                                cell = new[] {
//                                            e.BlockId.ToString(),
//                                            e.BlockName,
//                                            e.SeriesId.ToString(),
//                                            e.BlockDescription,
//                                            e.BlockSize,
//                                            e.BlockWidth.ToString(),
//                                            e.BlockHeight.ToString(),
//                                            e.BlockDepth.ToString(),
//                                            e.BlockWeigthLimit.ToString(),
//                                            e.BlockOutlineUrl,
//                                            e.BlockCreateDate.ToLongDateString(),
//                                            e.BlockCreateBy.ToString(),
//                                            e.BlockUpdateDate.ToLongDateString(),
//                                            e.BlockUpdateBy.ToString()
//                                            }
//                            }
//                        ).ToPagedList(1, pageSize).ToArray()
//            };
//            return jsonData;
//        }
    }
}



